<template>
  <div class="report-management">
    <el-row :gutter="24">
      <!-- 左侧上传区域 -->
      <el-col :xs="24" :md="10" class="upload-section">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <h2>上传威胁情报报告</h2>
              <el-tooltip content="上传后的报告可用于后续威胁情报抽取">
                <el-icon><el-icon-question-filled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          
          <el-upload
            class="report-uploader"
            drag
            action="#"
            :auto-upload="false"
            :http-request="handleCustomUpload"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :limit="5"
            :file-list="uploadFiles"
            multiple
          >
            <el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持txt, pdf, docx, html等多种格式文件，每个文件不超过10MB
              </div>
            </template>
          </el-upload>
          
          <div class="upload-actions" v-if="uploadFiles.length > 0">
            <el-button 
              type="primary" 
              @click="uploadAllFiles" 
              :loading="uploading"
              :disabled="uploading"
            >
              上传所有文件
            </el-button>
            <el-button 
              @click="clearFiles" 
              :disabled="uploading"
            >
              清空列表
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧报告列表 -->
      <el-col :xs="24" :md="14" class="reports-section">
        <el-card class="reports-card">
          <template #header>
            <div class="card-header">
              <h2>已上传报告</h2>
              <div class="header-actions">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索报告..."
                  prefix-icon="Search"
                  clearable
                  style="width: 220px"
                  @input="searchReports"
                />
                <el-button 
                  type="primary" 
                  :icon="Refresh"
                  @click="fetchReports"
                  title="刷新列表"
                  circle
                />
              </div>
            </div>
          </template>
          
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="4" animated />
          </div>
          
          <div v-else-if="reports.length === 0" class="empty-container">
            <el-empty description="暂无上传报告" />
          </div>
          
          <el-scrollbar height="500px" v-else>
            <div class="report-list">
              <div v-for="report in filteredReports" :key="report.id" class="report-item">
                <div class="report-info">
                  <div class="report-title">
                    <el-icon><el-icon-document /></el-icon>
                    {{ report.title || report.filename }}
                  </div>
                  <div class="report-meta">
                    <span class="upload-time">{{ formatDate(report.uploadTime) }}</span>
                    <el-tag size="small" :type="getReportStatusType(report.status)">
                      {{ getReportStatusText(report.status) }}
                    </el-tag>
                  </div>
                  <div class="report-summary" v-if="report.summary">
                    {{ truncateText(report.summary, 80) }}
                  </div>
                </div>
                <div class="report-actions">
                  <el-tooltip content="查看详情">
                    <el-button 
                      type="primary" 
                      :icon="View"
                      @click="viewReport(report)"
                      circle
                      plain
                    />
                  </el-tooltip>
                  <el-tooltip content="提取情报">
                    <el-button 
                      type="success" 
                      :icon="DataAnalysis"
                      @click="extractIntel(report)"
                      circle
                      plain
                    />
                  </el-tooltip>
                  <el-tooltip content="删除报告">
                    <el-button 
                      type="danger" 
                      :icon="Delete"
                      @click="confirmDeleteReport(report)"
                      circle
                      plain
                    />
                  </el-tooltip>
                </div>
              </div>
            </div>
          </el-scrollbar>
          
          <div class="pagination-container" v-if="reports.length > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalReports"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 报告详情对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="报告详情"
      width="70%"
      top="5vh"
    >
      <div v-if="currentReport" class="report-detail">
        <h3>{{ currentReport.title || currentReport.filename }}</h3>
        <div class="report-detail-meta">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="文件名">{{ currentReport.filename }}</el-descriptions-item>
            <el-descriptions-item label="上传时间">{{ formatDate(currentReport.uploadTime) }}</el-descriptions-item>
            <el-descriptions-item label="文件大小">{{ formatFileSize(currentReport.fileSize) }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="report-content">
          <div class="content-header">报告内容预览</div>
          <el-scrollbar height="400px">
            <pre class="content-text">{{ currentReport.content }}</pre>
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="extractIntel(currentReport)">
            提取情报
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  UploadFilled as ElIconUploadFilled,
  QuestionFilled as ElIconQuestionFilled,
  Document as ElIconDocument
} from '@element-plus/icons-vue';
import {
  View,
  Delete,
  Refresh,
  DataAnalysis
} from '@element-plus/icons-vue';

const router = useRouter();
const loading = ref(false);
const uploading = ref(false);
const uploadFiles = ref([]);
const reports = ref([]);
const currentReport = ref(null);
const reportDialogVisible = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalReports = ref(0);

// 模拟的报告数据
const mockReports = [
  {
    id: '1',
    filename: 'threat_report_2023.txt',
    title: '2023年网络威胁态势分析报告',
    uploadTime: new Date(2023, 10, 15).toISOString(),
    fileSize: 1024 * 512,
    status: 'processed',
    summary: '本报告分析了2023年全球主要的网络威胁态势，包括勒索软件、供应链攻击和APT组织活动。',
    content: '近年来，随着数字化转型的加速，网络安全威胁呈现多样化、复杂化的趋势。勒索软件攻击仍是2023年最主要的网络威胁之一，攻击者不仅加密受害者数据，还威胁公开窃取的敏感信息，实施"双重勒索"。\n\n供应链攻击成为新的焦点，攻击者通过篡改软件更新或开源组件，一次性感染大量目标。APT组织活动更趋活跃，多国支持的黑客组织针对关键基础设施、政府机构和研究机构发起持续性攻击。'
  },
  {
    id: '2',
    filename: 'apt28_analysis.pdf',
    title: 'APT28组织活动分析',
    uploadTime: new Date(2023, 9, 28).toISOString(),
    fileSize: 1024 * 1024 * 2.3,
    status: 'processing',
    summary: '详细分析了APT28（Fancy Bear）组织的最新攻击手法、工具和目标。',
    content: 'APT28（又称Fancy Bear、Sofacy）是一个据信与俄罗斯军事情报机构GRU有关联的高级持续性威胁（APT）组织。该组织自2007年以来一直活跃，主要针对政府、军事和安全组织。\n\n最新观察表明，APT28已经更新了其攻击工具集，采用新的零日漏洞和社会工程学技术。该组织现在更多地使用鱼叉式钓鱼邮件作为初始攻击载体，邮件通常伪装成会议邀请或安全更新通知。'
  },
  {
    id: '3',
    filename: 'ransomware_trends.docx',
    title: '勒索软件最新趋势',
    uploadTime: new Date(2023, 8, 10).toISOString(),
    fileSize: 1024 * 768,
    status: 'failed',
    summary: '分析了2023年Q3勒索软件的发展趋势、新变种和防护建议。',
    content: '2023年第三季度，勒索软件攻击继续呈上升趋势，与去年同期相比增长了37%。值得注意的是，攻击者的目标选择更加精准，重点瞄准了医疗、教育和关键基础设施等行业。\n\n新出现的勒索软件变种如BlackCat、Royal和LockBit 3.0采用了更先进的规避技术和加密算法。这些组织还建立了专业的泄露网站，用于公布受害者数据，增加勒索的筹码。'
  }
];

// 初始加载报告列表
onMounted(() => {
  fetchReports();
});

// 过滤报告列表
const filteredReports = computed(() => {
  if (!searchQuery.value) {
    return reports.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return reports.value.filter(report => 
    (report.title && report.title.toLowerCase().includes(query)) ||
    report.filename.toLowerCase().includes(query) ||
    (report.summary && report.summary.toLowerCase().includes(query))
  );
});

// 获取报告列表
const fetchReports = async () => {
  loading.value = true;
  try {
    // 在实际应用中，这里应该调用API获取报告列表
    // const response = await axios.get('/api/reports', {
    //   params: { page: currentPage.value, pageSize: pageSize.value },
    //   headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    // });
    // reports.value = response.data.items;
    // totalReports.value = response.data.total;
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 600));
    
    // 使用模拟数据
    reports.value = mockReports;
    totalReports.value = mockReports.length;
  } catch (error) {
    console.error('获取报告列表失败:', error);
    ElMessage.error('获取报告列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理文件变化
const handleFileChange = (file) => {
  console.log('文件变化:', file);
};

// 处理文件移除
const handleFileRemove = (file) => {
  console.log('移除文件:', file);
};

// 自定义上传处理
const handleCustomUpload = async ({ file, onSuccess, onError }) => {
  try {
    // 在实际应用中，这里应该调用API上传文件
    // const formData = new FormData();
    // formData.append('file', file);
    // const response = await axios.post('/api/reports/upload', formData, {
    //   headers: {
    //     'Content-Type': 'multipart/form-data',
    //     Authorization: `Bearer ${localStorage.getItem('token')}`
    //   }
    // });
    
    // 模拟上传成功
    console.log('上传文件:', file.name);
    await new Promise(resolve => setTimeout(resolve, 1000));
    onSuccess({ filename: file.name });
  } catch (error) {
    console.error('上传文件失败:', error);
    onError('上传失败');
  }
};

// 上传所有文件
const uploadAllFiles = async () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件');
    return;
  }
  
  uploading.value = true;
  
  try {
    // 模拟上传过程
    await new Promise(resolve => setTimeout(resolve, 1500));
    ElMessage.success(`成功上传 ${uploadFiles.value.length} 个文件`);
    uploadFiles.value = [];
    fetchReports();
  } catch (error) {
    console.error('上传文件失败:', error);
    ElMessage.error('上传文件失败');
  } finally {
    uploading.value = false;
  }
};

// 清空文件列表
const clearFiles = () => {
  uploadFiles.value = [];
};

// 搜索报告
const searchReports = () => {
  // 过滤逻辑已在computed中处理
};

// 查看报告详情
const viewReport = (report) => {
  currentReport.value = report;
  reportDialogVisible.value = true;
};

// 提取情报
const extractIntel = (report) => {
  // 关闭对话框如果打开着
  reportDialogVisible.value = false;
  
  // 导航到情报提取页面并传递报告ID
  router.push({
    path: '/dashboard/extract',
    query: { reportId: report.id }
  });
};

// 确认删除报告
const confirmDeleteReport = (report) => {
  ElMessageBox.confirm(
    `确定要删除报告"${report.title || report.filename}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      deleteReport(report.id);
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 删除报告
const deleteReport = async (reportId) => {
  try {
    // 在实际应用中，这里应该调用API删除报告
    // await axios.delete(`/api/reports/${reportId}`, {
    //   headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    // });
    
    // 模拟删除
    await new Promise(resolve => setTimeout(resolve, 500));
    reports.value = reports.value.filter(report => report.id !== reportId);
    totalReports.value--;
    ElMessage.success('报告已删除');
  } catch (error) {
    console.error('删除报告失败:', error);
    ElMessage.error('删除报告失败');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return `${size}B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)}KB`;
  } else {
    return `${(size / (1024 * 1024)).toFixed(2)}MB`;
  }
};

// 获取报告状态类型
const getReportStatusType = (status) => {
  switch (status) {
    case 'processed':
      return 'success';
    case 'processing':
      return 'warning';
    case 'failed':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取报告状态文本
const getReportStatusText = (status) => {
  switch (status) {
    case 'processed':
      return '已处理';
    case 'processing':
      return '处理中';
    case 'failed':
      return '处理失败';
    default:
      return '未处理';
  }
};

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text || text.length <= maxLength) {
    return text;
  }
  return `${text.substring(0, maxLength)}...`;
};

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  fetchReports();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchReports();
};
</script>

<style scoped>
.report-management {
  width: 100%;
}

.upload-section, .reports-section {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.report-uploader {
  width: 100%;
}

.upload-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.loading-container, .empty-container {
  padding: 30px 0;
  text-align: center;
}

.report-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.report-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.report-item:hover {
  background-color: #f0f0f0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.report-info {
  flex: 1;
  min-width: 0;
}

.report-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  margin-bottom: 6px;
  font-size: 16px;
}

.report-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.report-summary {
  font-size: 14px;
  color: #606266;
  margin-top: 6px;
}

.report-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.report-detail {
  padding: 0 10px;
}

.report-detail h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
}

.report-detail-meta {
  margin-bottom: 20px;
}

.report-content {
  margin-top: 20px;
}

.content-header {
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 16px;
}

.content-text {
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  white-space: pre-wrap;
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #eaeaea;
  font-size: 14px;
  line-height: 1.6;
  overflow-wrap: break-word;
}

@media (max-width: 768px) {
  .report-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .report-actions {
    margin-top: 12px;
    align-self: flex-end;
  }
}
</style> 